package com.sgb.kjwl.view.ui.activity.leaseAsk.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.sgb.kjwl.AppConstant;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.FragmentAskLeaseFactory3Binding;
import com.sgb.kjwl.model.entity.AskLeaseFactoryEntity;
import com.sgb.kjwl.model.entity.self.SelfTeamIntroduceEntity;
import com.sgb.kjwl.view.ui.activity.self.packers.SelfServiceAreaActivity;
import com.sgb.kjwl.viewmodel.machine.AskLeaseCommonModel;
import com.sgb.kjwl.viewmodel.machine.AskLeaseFactoryModel2;
import com.swgk.core.customview.CfkEditView;
import com.swgk.core.util.MToast;
import com.swgk.core.util.PickSelectEntity;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class AskLeaseFactoryFragment3 extends Fragment {

    private FragmentAskLeaseFactory3Binding binding;
    private AskLeaseFactoryModel2 viewModel;
    private AskLeaseCommonModel commonModel;
    private List<PickSelectEntity> dataArray1 = new ArrayList<>();//报价人身份
    private List<PickSelectEntity> dataArray2 = new ArrayList<>();//报价人限定
    private OptionsPickerView pickerView1, pickerView2;

    private List<AskLeaseFactoryEntity.ParamBean> viewList = new ArrayList<>();//自定义参数

    private String id = "";


    public void onAttach(Context context) {
        super.onAttach(context);
        id = getArguments().getString("id");
    }

    public static AskLeaseFactoryFragment3 newInstance(String id) {
        AskLeaseFactoryFragment3 frag = new AskLeaseFactoryFragment3();
        Bundle bundle = new Bundle();
        bundle.putString("id", id);
        frag.setArguments(bundle);
        return frag;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_ask_lease_factory_3, container, false);
        binding.setLifecycleOwner(this);
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        viewModel = new ViewModelProvider(getActivity()).get(AskLeaseFactoryModel2.class);
        commonModel = new ViewModelProvider(this).get(AskLeaseCommonModel.class);
        initView();
        initData();
        showDetail();
    }

    private void initData() {
        dataArray1.add(new PickSelectEntity("0", "公司、个人皆可"));
        dataArray1.add(new PickSelectEntity("1", "仅限公司"));
        dataArray1.add(new PickSelectEntity("2", "仅限个人"));

        dataArray2.add(new PickSelectEntity("0", "不限"));
        dataArray2.add(new PickSelectEntity("1", "限企业注册地区"));

        showPop1();
        showPop2();
    }

    private void initView() {
        binding.beforeAndPubishItem.tvSubmit.setOnClickListener(v -> onPublish());
        binding.beforeAndPubishItem.tvBeforeStep.setOnClickListener(v -> viewModel.selectFragLiveData.postValue(1));
        binding.beforeAndPubishItem.tvBeforeStep.setOnClickListener(v -> viewModel.selectFragLiveData.postValue(1));
        binding.itvIdentity.setOnWholeItemClickListener(view -> pickerView1.show());
        binding.itvXianDing.setOnWholeItemClickListener(view -> pickerView2.show());
        binding.itvZhuCe.setOnWholeItemClickListener(view -> showRegistrationArea());
        binding.tvAddView.setOnClickListener(v -> addView());
        binding.tvDelView.setOnClickListener(v -> delView());

    }

    /**
     * 报价人身份
     */
    private void showPop1() {
        pickerView1 = new OptionsPickerBuilder(getActivity(), (options1, options2, options3, v) -> {
            String content = dataArray1.get(options1).getProjectscale();
            binding.itvIdentity.setContent(content);
            viewModel.entity.getAttach().setIdentity(dataArray1.get(options1).getNo());
            if (content.equals("仅限个人")) {
                binding.itvXianDing.setVisibility(View.GONE);
                binding.itvZhuCe.setVisibility(View.GONE);
            } else {
                binding.itvXianDing.setVisibility(View.VISIBLE);
                pickerView2.setSelectOptions(0);
                binding.itvXianDing.setContent("不限");
                binding.itvZhuCe.setVisibility(View.GONE);
            }
        }).build();
        pickerView1.setPicker(dataArray1);
        pickerView1.setSelectOptions(0);
    }

    /**
     * 报价人限定
     */
    private void showPop2() {
        pickerView2 = new OptionsPickerBuilder(getActivity(), (options1, options2, options3, v) -> {
            String content = dataArray2.get(options1).getProjectscale();
            binding.itvXianDing.setContent(content);
            viewModel.entity.getAttach().setLimited(dataArray2.get(options1).getNo());
            if (content.equals("限企业注册地区")) {
                binding.itvZhuCe.setVisibility(View.VISIBLE);
            } else {
                binding.itvZhuCe.setVisibility(View.GONE);
                if (viewModel.entity.getAttach().getRegistrationArea() != null) {
                    viewModel.entity.getAttach().getRegistrationArea().clear();
                }
            }
        }).build();
        pickerView2.setPicker(dataArray2);
        pickerView2.setSelectOptions(0);
    }

    private void addView() {
        if (binding.llDescGroup.getChildCount() >= 5) {
            MToast.showToast(getActivity(), "最多只能新增5条");
            return;
        }
        if (!getViewList()) {
            return;
        }
        View view = View.inflate(getActivity(), R.layout.layout_lease_ask_item, null);
        binding.llDescGroup.addView(view, binding.llDescGroup.getChildCount());
        TextView tvDel = view.findViewById(R.id.tv_del);
        tvDel.setOnClickListener(view1 -> binding.llDescGroup.removeView(view));
        if (binding.llDescGroup.getChildCount() > 1) {
            View itemView = binding.llDescGroup.getChildAt(binding.llDescGroup.getChildCount() - 2);
            itemView.findViewById(R.id.tv_del).setVisibility(View.VISIBLE);
        }
        binding.tvDelView.setVisibility(View.VISIBLE);
    }

    private void delView() {
        if (binding.llDescGroup.getChildCount() > 0) {
            binding.llDescGroup.removeViewAt(binding.llDescGroup.getChildCount() - 1);
            if (binding.llDescGroup.getChildCount() == 0) {
                binding.tvDelView.setVisibility(View.GONE);
            } else {
                View itemView = binding.llDescGroup.getChildAt(binding.llDescGroup.getChildCount() - 1);
                itemView.findViewById(R.id.tv_del).setVisibility(View.GONE);
            }
        }

    }

    public boolean getViewList() {
        viewList.clear();
        for (int i = 0; i < binding.llDescGroup.getChildCount(); i++) {
            View view = binding.llDescGroup.getChildAt(i);
            String title = ((EditText) view.findViewById(R.id.tv_desc_title)).getText().toString().trim();
            String content = ((CfkEditView) view.findViewById(R.id.tv_desc_content)).getEditContent().trim();
            if (TextUtils.isEmpty(title) || TextUtils.isEmpty(content)) {
                MToast.showToast(getActivity(), "请完善新增说明");
                return false;
            }
            AskLeaseFactoryEntity.ParamBean bean = new AskLeaseFactoryEntity.ParamBean();
//            bean.setNo(i);
            bean.setTitle(title);
            bean.setContent(content);
            viewList.add(bean);
        }
        return true;
    }

    public boolean getViewList2() {
        viewList.clear();
        for (int i = 0; i < binding.llDescGroup.getChildCount(); i++) {
            View view = binding.llDescGroup.getChildAt(i);
            String title = ((EditText) view.findViewById(R.id.tv_desc_title)).getText().toString().trim();
            String content = ((CfkEditView) view.findViewById(R.id.tv_desc_content)).getEditContent().trim();
            if (TextUtils.isEmpty(title) && !TextUtils.isEmpty(content)) {
                MToast.showToast(getActivity(), "请完善新增说明");
                return false;
            }
            if (!TextUtils.isEmpty(title) && TextUtils.isEmpty(content)) {
                MToast.showToast(getActivity(), "请完善新增说明");
                return false;
            }
            if (!TextUtils.isEmpty(title) && !TextUtils.isEmpty(content)) {
                AskLeaseFactoryEntity.ParamBean bean = new AskLeaseFactoryEntity.ParamBean();
                //bean.setNo(i);
                bean.setTitle(title);
                bean.setContent(content);
                viewList.add(bean);
            }
        }
        return true;
    }

    private void showDetail() {
        if (!TextUtils.isEmpty(id)) {
            binding.cetOvertime.setEditContent(viewModel.entity.getAttach().getOvertimeEnterFactory());
            binding.cetMachineryUnqualified.setEditContent(viewModel.entity.getAttach().getMachineryUnqualified());
            if ("2".equals(viewModel.entity.getAttach().getIdentity())) {
                //报价人身份仅限个人时，隐藏报价人限定
                binding.itvXianDing.setVisibility(View.GONE);
                binding.itvZhuCe.setVisibility(View.GONE);
            } else {
                binding.itvXianDing.setVisibility(View.VISIBLE);
                if ("0".equals(viewModel.entity.getAttach().getLimited())) {
                    //报价人限定为不限时，隐藏企业注册地
                    binding.itvZhuCe.setVisibility(View.GONE);
                } else {
                    binding.itvZhuCe.setVisibility(View.VISIBLE);
                }
            }
            try {
                if (!TextUtils.isEmpty(viewModel.entity.getAttach().getIdentity()) && dataArray1.size() > 0) {
                    binding.itvIdentity.setContent(dataArray1.get(Integer.parseInt(viewModel.entity.getAttach().getIdentity())).getPickerViewText());
                }
                if (!TextUtils.isEmpty(viewModel.entity.getAttach().getLimited()) && dataArray2.size() > 0) {
                    binding.itvXianDing.setContent(dataArray2.get(Integer.parseInt(viewModel.entity.getAttach().getLimited())).getPickerViewText());
                }
            } catch (Exception ex) {
            }
            //附加字段返显
            if (viewModel.entity.getAttach().getDeduction() != null && viewModel.entity.getAttach().getDeduction().size() > 0) {
                for (int i = 0; i < viewModel.entity.getAttach().getDeduction().size(); i++) {
                    AskLeaseFactoryEntity.ParamBean param = viewModel.entity.getAttach().getDeduction().get(i);
                    View view = View.inflate(getActivity(), R.layout.layout_lease_ask_item, null);
                    ((EditText) view.findViewById(R.id.tv_desc_title)).setText(param.getTitle());
                    ((CfkEditView) view.findViewById(R.id.tv_desc_content)).setEditContent(param.getContent());
                    binding.llDescGroup.addView(view, i);
                    //删除按钮
                    TextView tvDel = (TextView) view.findViewById(R.id.tv_del);
                    tvDel.setVisibility(View.VISIBLE);
                    tvDel.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            binding.llDescGroup.removeView(view);
                        }
                    });
                    if (i == viewModel.entity.getAttach().getDeduction().size() - 1) {
                        tvDel.setVisibility(View.GONE);
                        binding.tvAddView.setVisibility(View.VISIBLE);
                        binding.tvDelView.setVisibility(View.VISIBLE);
                    }
                }
            }
            if (viewModel.entity.getAttach().getRegistrationArea() != null && viewModel.entity.getAttach().getRegistrationArea().size() > 0) {
                binding.itvZhuCe.setContent("已选择" + viewModel.entity.getAttach().getRegistrationArea().size() + "个城市");
            }
        }
    }

    private void onPublish() {
//        if (binding.itvZhuCe.getVisibility() == View.VISIBLE && TextUtils.isEmpty(binding.itvZhuCe.getContent())) {
//            MToast.showToast(getActivity(), "请选择企业注册地");
//            return;
//        }
        if (getViewList2()) {
            viewModel.entity.getAttach().setDeduction(viewList);
        } else {
            return;
        }
        viewModel.entity.getAttach().setOvertimeEnterFactory(binding.cetOvertime.getEditContent());
        viewModel.entity.getAttach().setMachineryUnqualified(binding.cetMachineryUnqualified.getEditContent());
        if (TextUtils.isEmpty(viewModel.entity.getAttach().getIdentity())) {
            viewModel.entity.getAttach().setIdentity("0");//未选择，则默认第一项
        }
        if (TextUtils.isEmpty(viewModel.entity.getAttach().getLimited())) {
            viewModel.entity.getAttach().setLimited("0");//未选择，则默认第一项
        }
        viewModel.addOrupdate(viewModel.entity);
    }

    //限制企业注册地区选择
    private void showRegistrationArea() {
        List<SelfTeamIntroduceEntity.ServiceAreasBean> areasBeanList = new ArrayList<>();
        if (viewModel.entity.getAttach() != null && viewModel.entity.getAttach().getRegistrationArea() != null) {
            for (AskLeaseFactoryEntity.AreaBean bean :
                    viewModel.entity.getAttach().getRegistrationArea()) {
                SelfTeamIntroduceEntity.ServiceAreasBean areasBean = new SelfTeamIntroduceEntity.ServiceAreasBean();
                areasBean.setAreaNo(bean.getNo());
                areasBean.setName(bean.getName());
                areasBeanList.add(areasBean);
            }
        }
        Intent intent = new Intent();
        intent.setClass(getActivity(), SelfServiceAreaActivity.class);
        intent.putExtra(AppConstant.EXTRA_ENTITY, (Serializable) areasBeanList);
        intent.putExtra("title", "选择地区");
        startActivityForResult(intent, 10101);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK && requestCode == 10101 && data != null) {
            try {
                List<SelfTeamIntroduceEntity.ServiceAreasBean> areaList = (List<SelfTeamIntroduceEntity.ServiceAreasBean>) data.getSerializableExtra(AppConstant.EXTRA_OBJ);
                List<AskLeaseFactoryEntity.AreaBean> beanList = new ArrayList<>();
                for (SelfTeamIntroduceEntity.ServiceAreasBean bean :
                        areaList) {
                    AskLeaseFactoryEntity.AreaBean areaBean = new AskLeaseFactoryEntity.AreaBean();
                    areaBean.setNo(bean.getAreaNo());
                    areaBean.setName(bean.getName());
                    beanList.add(areaBean);
                }
                viewModel.entity.getAttach().setRegistrationArea(beanList);
                binding.itvZhuCe.setContent("已选择" + beanList.size() + "个城市");
            } catch (Exception ex) {
            }

        }
    }
}
